package com.whisperarts.financer.app.actions;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;
import org.eclipse.ui.plugin.AbstractUIPlugin;

import com.whisperarts.financer.app.Application;
import com.whisperarts.financer.app.dialogs.EditCategoryDialog;
import com.whisperarts.financer.app.utils.UIUtils;
import com.whisperarts.financer.dao.AccountsDAO;
import com.whisperarts.financer.model.transaction.Category;

public class EditCategoryAction extends Action implements 
ISelectionListener, IWorkbenchAction {

	private final IWorkbenchWindow window;
	public final static String ID = "com.whisperarts.financer.app.actions.editCategory";
	private IStructuredSelection selection;


	public EditCategoryAction(IWorkbenchWindow window) {
		this.window = window;
		setId(ID);
		setText("&Edit category");
		setToolTipText("Edit selected category");
		setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin(Application.PLUGIN_ID, ISharedImages.IMG_ETOOL_SAVE_EDIT));
		window.getSelectionService().addSelectionListener(this);
	}

	@Override
	public void selectionChanged(IWorkbenchPart part, ISelection incoming) {
		if (incoming instanceof IStructuredSelection) {
			selection = (IStructuredSelection) incoming;
			setEnabled(selection.size() == 1);
		} else {
			setEnabled(false);
		}
	}

	@Override
	public void dispose() {
		window.getSelectionService().removeSelectionListener(this);
	}

	@Override
	public void run() {
		Category editingCategory = (Category)selection.getFirstElement();
		int prevParentId = editingCategory.getParentId();
		EditCategoryDialog d = new EditCategoryDialog(window.getShell(), editingCategory);
		if (d.open() == Window.OK) {
			editingCategory = d.getCategory();
			if (AccountsDAO.updateCategory(editingCategory) == 0) {
				Category prevParent = d.getAdapter().getCategoryById(prevParentId);
				Category newParent = d.getAdapter().getCategoryById(editingCategory.getParentId());
				if (prevParent.getId() != newParent.getId()) {
					prevParent.getSub().remove(editingCategory);
					newParent.getSub().add(editingCategory);
				}
				if (prevParent.getId() == 0 || newParent.getId() == 0) {
					UIUtils.refreshCategoryNode();
				} else { 
					UIUtils.refreshCategoryNode(prevParent, newParent);
				}
			}
		}

	}
}
